<template>
  <div class="learning">
    <div class="chaptername">
      <span>{{chapter.cid}}、</span>
      <span>{{chapter.chaptersName}}</span>
    </div>
    <el-alert
      :title='"即将播放下一个课程视频" +"  "+ time'
      type="success"
      close-text="立刻跳转"
      @close = 'goNextLearn'
      v-if='playend'>
    </el-alert>
    <el-alert
      title="撒花#v#  恭喜主人完成了一个课程的学习"
      type="success"
      v-if='classend'>
    </el-alert>
    <div class="playvideowrapper">
      <span class="iconfont icon-zhangjie" @click="draw"></span>
      <span>章节列表</span>
      <el-drawer
        title="课程列表"
        :visible.sync="drawer"
        :with-header="false"
        direction="ltr"
        size="190"
        >
        <div class="chapterslist" @click="goOtherlearning">
          <div class="chapters" v-for="(item,index) in classinfo.content" :key="index">
            <span :data-cid="item.chaptersNo">{{item.cid}}、{{item.chaptersName}}</span>
          </div>
        </div>
      </el-drawer>
      <div class="playvideo">
        <video id="myvideo" class="video-js vjs-big-play-centered">
          <source :src="videosource" type="video/mp4">
        </video>
      </div>
    </div>
    <div class="tab">
      <threetab :showchapter='showchapter'></threetab>
    </div>
  </div>
</template>
<script>
import threetab from '@/components/threetab.vue'
import axios from 'axios'
import {mapState} from 'vuex'
export default {
  name: 'learning',
  data () {
    return {
      showchapter: false,
      videosource: null,
      classinfo: {},
      chapter: {},
      playend: false,
      drawer: false,
      time: 3,
      classend: false,
      timer: null
      // mediaSource: null,
      // sourceBuffer: null,
      // myPlayer: null,
    }
  },
  computed:{
    ...mapState({
      memberNo: 'memberNo',
    }),
  },
  inject: ['reload'],
  methods: {
    getvideosource () {
      let cid = this.$route.query.chapterId
      let path = this.ports.learning.getChapterVideo
      let mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'
      let video = document.getElementById('v1')
      let mediaSource
      let that = this
      if('MediaSource' in window && MediaSource.isTypeSupported(mimeCodec)) {
        console.log('MediaSource')
        mediaSource = new MediaSource()
        video.src = URL.createObjectURL(mediaSource)
        mediaSource.addEventListener('sourceopen',sourceOpen.bind(this))
      } else{
        console.error('Unsupported MIME type or codec:',mimeCodec)   
      }
      function sourceOpen () {
        console.log('has opened')
        URL.revokeObjectURL(video.src)
        let sourceBuffer = mediaSource.addSourceBuffer(mimeCodec)
        fetchAB(path,sourceBuffer)
      }
      function fetchAB (url,sourceBuffer) {
        axios.get(url).then((result)=>{
          console.log(Object.prototype.toString.call(result.data));
          // console.log(result.data);
          // let data = new Blob([result.data],{type: 'application/octet-stream'})
          // console.log(Object.prototype.toString.call(data));
          // console.log(data);
          // var reader = new FileReader();
          // reader.onload = function() {
          //   console.log(this.result);
          // }
          // reader.readAsArrayBuffer(blob);
          function toArrayBuffer(buf) {
            var ab = new ArrayBuffer(buf.length);
            var view = new Uint8Array(ab);
            for (var i = 0; i < buf.length; ++i) {
                view[i] = buf[i];
            }
            return ab;
          }
          let r = toArrayBuffer(result.data)
          console.log(Object.prototype.toString.call(r))
          sourceBuffer.addEventListener('updateend', function () {
            console.log(mediaSource.readyState);
            console.log(sourceBuffer)
            console.log(mediaSource);
            mediaSource.endOfStream()
          })
          sourceBuffer.appendBuffer(r)
        })
      }
    },
    getvideo () {
      this.videosource = 'http://134.175.176.48:3000/api/chapter/learning/video?chaptersNo=000001'
    },
    initVideo () {
      let that = this
      this.$nextTick(()=>{
        let myPlayer = this.$video('myvideo', {
          controls: true,
          preload: "auto",
          // sources: [
          //   {
          //     src: '',
          //     type: 'video/mp4'
          //   }
          // ]
          width: "1000px",
          // height: "400px"
        }, function() {
          // 播放完毕回调
          this.on('ended',() => {
            if (that.chapter.cid < that.classinfo.content.length) {
              that.playend = true
              that.timer = setInterval(() => {
                that.time--
                console.log(that.time)
                if(that.time === 0) {
                  that.goNextLearn()
                  clearInterval(that.timer)
                }
              }, 1000);
            } else {
              console.log('study end');
              that.classend = true
            }
          })
        });
      })
    },
    getbasesource () {
      let cid = this.$route.query.chapterId
      axios.get(this.ports.chapter.chapterBaseInfo + '?chaptersNo=' + cid)
        .then(this.getbasesourceSucc)
    },
    getbasesourceSucc (res) {
      let result = res.data.result
      if (result.code === 200 && res.status === 200) {
        this.chapter = result.msg
        console.log(this.chapter)
      }
    },
    draw () {
      this.drawer = true
    },
    // 课程章节列表
    getChapterInfo () {
      let classNo = this.$route.query.classNo
      console.log(classNo)
      this.common.sendajax(classNo).then((data) => {
        this.classinfo = data
        console.log('classinfo');
        console.log(this.classinfo)
      })
    },
    goNextLearn () {
      console.log(this.chapter.cid,  this.classinfo.content.length)
      let chapterId
      for (let item of this.classinfo.content) {
        if(item.cid === this.chapter.cid + 1) {
          chapterId = item.chaptersNo
          break;
        }
      }
      let myPlayer = this.$video('myvideo', {})
      myPlayer.dispose()
      let classNo = this.$route.query.classNo
      this.$router.push({
        path: '/learning',
        query: {
          classNo,
          chapterId
        }
        
      }).catch(err => {
        console.log(err);
      })
    },
    goOtherlearning (e) {
      let chapterId = event.target.dataset.cid
      console.log(chapterId)
      let classNo = this.$route.query.classNo
      let routeData = this.$router.resolve({
        path: '/learning',
        query: { 
          classNo: this.$route.query.classNo,
          chapterId
        },
      });
      window.open(routeData.href, '_blank');
    },
    beforeunloadFn () {
      let data = {
        memberNo : this.memberNo,
        chapterId: this.$route.query.chapterId,
        // studySpeed: ,
      }
      // if(this.playend) {
      //   // 更新学习进度
      //   this.http.post(this.ports.learning.setLearningSpeed, data, res=>{

      //   })
      // }
      
    }
  },
  mounted () {
    this.getbasesource()
    this.getChapterInfo()
    // this.getvideosource()
    this.initVideo()
    this.getvideo()
    window.addEventListener('beforeunload', e => this.beforeunloadFn(e))
  },
  destroyed() {
    window.removeEventListener('beforeunload', e => this.beforeunloadFn(e))
  },
  watch:{
    '$route': function () {
      console.log('route change');
      this.reload()
      clearInterval(this.timer)
    }
  },
  components: {
    threetab
  }
}
</script>
<style lang="scss" scoped>
.learning {
  width:auto;
  height: auto;
}
.tab{
  width: 800px;
  height: auto;
  margin: 40px auto;
}
.playvideowrapper{
  width: 100%;
  height: auto;
  margin: 0 auto;
  background: #1c1f21;
  padding:30px 0;
  display: flex;
  align-items: center;
  position: relative;
  color:#fff;
  .icon-zhangjie{
    font-size:30px;
  }
  span{
    font-size: 16px;
    margin-left: 10px;
  }
}
.chapterslist{
  width: 100%;
  height: auto;
  padding: 0 20px;
}
.chapters{
  width: 100%;
  font-size:16px;
  height: auto;
  span{
    padding:10px 0;
    display: block;
  }
}
.playvideo{
  width: 90%;
  height: auto;
  background: #000;
  margin: 0 auto;
  display: flex;
  justify-content: center;
}
.chaptername{
  padding:0 110px;
  margin:20px 0;
}
.el-alert{
  width: 70% !important;
  margin: 0 auto;
}
.el-drawer{
  width: 100% !important;
}
</style>
